var urlDocumento = $("#urlDocumento").attr('value');

$(document).ready(function(){
	$('<input type="button" id="button_add_transclusion" value="Create transclusion!"/>').insertBefore("#urlDocumento");

	$("#transclusionmenu").css({
		"font-family":"courier",
		"text-align" : "left",
		"color" : "#000",

		"position" : "fixed",
		"bottom" : "1%",
		"left" : "1%",

		"width" : "200px"
	});

	$("#source_article").click(function(){
		urlSourceArticle = "source_article";
		sourceChecked = true;

		if( $(this).is(':checked') ){
			urlSourceArticle = extractPageName( document.URL );
			$("#source_article_name").html("<b>" + urlSourceArticle + "</b>");
		}
		else{
			sourceChecked = false;
			$("#source_article_name").html("[source]");
		}

		sajax_do_call('registerGlobalFlagST', ["source" , sourceChecked , urlSourceArticle] , function(data){
			$("#source_article_name").append(data.responseText);
		});
	}).change(showOrHideButton);

	$("#target_article").click(function(){
		urlTargetArticle = "target_article";
		targetChecked = true;

		if( $(this).is(':checked') ){
			urlTargetArticle = extractPageName( document.URL );
			$("#target_article_name").html("<b>" + urlTargetArticle + "</b>");
		}
		else{
			targetChecked = false;
			$("#target_article_name").html("[target]");
		}

		sajax_do_call('registerGlobalFlagST', ["target" , targetChecked , urlTargetArticle] , function(data){
			$("#target_article_name").append(data.responseText);
		});
	}).change(showOrHideButton);

	showOrHideButton();

	$("#button_add_transclusion").click(function(){
		sajax_do_call('getParametersOfTransclusion',[],function(data){
			openNewWindow(urlDocumento + 'visualization/index.php?' + data.responseText);
		});
	});
	
	$("#openWUV").css({
	}).click(function(){
		openNewWindow( urlDocumento + 'wuv/index.php' );
	});
});

function showOrHideButton(){
	if( $("#target_article").is(':checked') && $("#source_article").is(':checked') ){
		$("#button_add_transclusion").show();
	}
	else{
		$("#button_add_transclusion").hide();
	}
}

function extractPageName(url){
	var pageName;

	// Se ubica el nombre de la p�gina
	lastIndexSlash = url.lastIndexOf("/") + 1;

	// Se ubica un # en caso que exista
	lastIndexNumeral = url.lastIndexOf("#");

	// Si no existe #
	if(lastIndexNumeral == -1){
		pageName = url.substring(lastIndexSlash);
	}
	else{
		pageName = url.substring(lastIndexSlash , lastIndexNumeral);
	}

	return pageName;
}

function openNewWindow(url){
	$(document).ready(function(){
		title = "Transclusion Manager";
		specs = "toolbar=no,menubar=no,height=800,width=1000";

		window.open(url,title,specs,false);
	});
}